import { NativeModules, DeviceEventEmitter } from 'react-native';

const { DatabaseModule } = NativeModules;

export interface DatabaseResult {
  id?: number;
  message: string;
  deletedCount?: number;
}

export interface Card {
  id: number;
  title: string;
  front_image: string;
  back_text: string;
  audio_path?: string;
  uuid?: string;
  created_at: string;
  updated_at: string;
}

class DatabaseService {
  /**
   * 保存卡片到本地数据库
   */
  async saveCard(card: Omit<Card, 'id'>, serverInfo?: any): Promise<DatabaseResult> {
    try {
      const result = await DatabaseModule.saveCard(card, serverInfo);
      return result;
    } catch (error) {
      console.error('保存卡片失败:', error);
      throw error;
    }
  }

  /**
   * 获取本地所有卡片
   */
  async getLocalCards(): Promise<Card[]> {
    try {
      const cards = await DatabaseModule.getLocalCards();
      return cards;
    } catch (error) {
      console.error('获取本地卡片失败:', error);
      throw error;
    }
  }

  /**
   * 删除卡片
   */
  async deleteCard(cardId: number): Promise<DatabaseResult> {
    try {
      const result = await DatabaseModule.deleteCard(cardId);
      return result;
    } catch (error) {
      console.error('删除卡片失败:', error);
      throw error;
    }
  }

  /**
   * 获取卡片数量
   */
  async getCardCount(): Promise<number> {
    try {
      const count = await DatabaseModule.getCardCount();
      return count;
    } catch (error) {
      console.error('获取卡片数量失败:', error);
      throw error;
    }
  }

  /**
   * 监听卡片保存事件
   */
  onCardSaved(callback: (result: DatabaseResult) => void) {
    return DeviceEventEmitter.addListener('onCardSaved', callback);
  }

  /**
   * 监听卡片删除事件
   */
  onCardDeleted(callback: (result: DatabaseResult) => void) {
    return DeviceEventEmitter.addListener('onCardDeleted', callback);
  }
}

export default new DatabaseService(); 